package com.jichangxiu.framework.utils;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.TimeUnit;

public class LockUtils {

    public static synchronized boolean lock(String lockKey, String clientId, long seconds) {
        // SET命令的参数
        String value = RedisUtils.getCacheObject(lockKey);
        if (StrUtil.isEmpty(value)) {
            RedisUtils.setCacheObject(lockKey, clientId, seconds, TimeUnit.SECONDS);
            return true;
        } else return false;
    }

    public static synchronized boolean unlock(String lockKey, String clientId) {
        String value = RedisUtils.getCacheObject(lockKey);
        // 如果过期了也能解锁成功
        if (StrUtil.isEmpty(value)) return true;
        else
            // 如果取出来不为空
            if (clientId.equals(value)) {
                // 并且 uuid 相等就解锁成功
                RedisUtils.deleteObject(lockKey);
                return true;
            }
        return false;
    }

}
